package com.cenxi.ipdemo1.controller;

import com.cenxi.ipdemo1.utils.GetClientIP;
import com.cenxi.ipdemo1.utils.IdGenerator;
import com.cenxi.ipdemo1.utils.IntToBinary36Utils;
import com.cenxi.ipdemo1.utils.Ip2RegionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/ip2region")
@Slf4j
public class Ip2RegionChangeController {

    @Autowired
    private Ip2RegionUtil regionUtil;

    @GetMapping("/getIpToAddress")
    public String getIpToAddressNoIp(HttpServletRequest request){
        String userIp = GetClientIP.getUserIpAddress(request);
        String ipAddress = regionUtil.changeIpToAddress(userIp);
        log.info("ip地址：{}，解析结果：{}",userIp,ipAddress);
        return ipAddress;
    }
    @GetMapping("/getIpToAddress/{ip}")
    public String getIpToAddress(@PathVariable("ip") String ip){
        String ipAddress = regionUtil.changeIpToAddress(ip);
        log.info("ip地址：{}，解析结果：{}",ip,ipAddress);
        return ipAddress;
    }

    /*
     * 短链接
     */
    @GetMapping("/shortUrl/{code}")
    public void shortUrl(@PathVariable("code") String code, HttpServletResponse response) {
        Map<String, String> map = new HashMap<>();
        map.put("baidu", "http://www.baidu.com/"+IntToBinary36Utils.change10To36(IdGenerator.generateId()+""));
        response.setHeader("cenxi", "cenxi");
        try {
            response.setStatus(HttpServletResponse.SC_FOUND);
            String url = map.get(code);
            if (url != null) {
                response.sendRedirect(url);
            } else {
                sendErrorMsg(response, code);
            }
        } catch (Exception e) {
            try {
                sendErrorMsg(response, code);
            } catch (IOException ex) {
                log.error("短链接错误: {}", ex.getMessage());
            }
        }
    }

    private void sendErrorMsg(HttpServletResponse response, String code) throws IOException {
        String msg = "<h3>短链接错误: "+code+"</h3>";
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        response.getOutputStream().write(msg.getBytes(StandardCharsets.UTF_8));
    }
}
